﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CadClient.CadHelpers
{
    public static class EntityHelper
    {
        /// <summary>
        /// 将图形添加到图形数据库
        /// </summary>
        /// <param name="db"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static ObjectId AddEntityToModelSpace(this Database db, Entity entity)
        {
            ObjectId entityObjectId = ObjectId.Null;
            using (var trans = db.TransactionManager.StartTransaction())
            {
                var bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                var btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                entityObjectId = btr.AppendEntity(entity);
                trans.AddNewlyCreatedDBObject(entity, true);
                trans.Commit();
            }
            return entityObjectId;
        }
        public static List<ObjectId> AddEntityTModelSpce(this Database db, params Entity[] entitys)
        {
            var entityObjectIds = new List<ObjectId>();
            using (var trans = db.TransactionManager.StartTransaction())
            {
                var bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                var btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                for (int i = 0; i < entitys.Length; i++)
                {
                    entityObjectIds.Add(btr.AppendEntity(entitys[i]));
                    trans.AddNewlyCreatedDBObject(entitys[i], true);
                }
                trans.Commit();
            }
            return entityObjectIds;
        }
        /// <summary>
        /// 直线添加到图形数据库
        /// </summary>
        /// <param name="db"></param>
        /// <param name="startPoint"></param>
        /// <param name="endPoint"></param>
        /// <returns></returns>
        public static ObjectId AddLineToModelSpace(this Database db, Point3d startPoint, Point3d endPoint)
        {
            return db.AddEntityToModelSpace(new Line(startPoint, endPoint));
        }
        public static Line AddLineToModelSpace1(this Database db, Point3d startPoint, Point3d endPoint)
        {
            var line = new Line(startPoint, endPoint);
            db.AddEntityToModelSpace(line);
            return line;
        }

    }
}
